/* eslint-disable */
import React, { useState } from 'react';
import { AntdBaseTable } from './TBaseTable';
import { Tooltip } from 'antd';
import { useTablePipeline, features } from 'ali-react-table';
import styles from './index.less';
import {
  CheckCircleOutlined,
  QuestionCircleOutlined,
  CloseCircleOutlined,
} from '#/utils/antdIcons.js';
import { SORT, tableDetailList } from '../../helper';
import _ from 'lodash';

const BaseTable = (props: any) => {
  const { tableData, tableHeader = [], text, issueStatusKeys } = props;
  // 处理表头
  const getColumns = (columsValue: any[]) => {
    const columns: any[] = [];
    columns.push({
      // name: '聚合维度', align: 'center', lock: true, width: 100,
      name: (
        <div className={styles.box}>
          <div className={styles.top}>聚合维度</div>
          <div className={styles.bottom}>{text}</div>
        </div>
      ),
      align: 'left',
      code: 'title',
      width: 130,
      lock: true,
      render: (value: any) => value || '-',
    });
    const group = _.groupBy(columsValue, 'parentName');
    const parentNames: any[] = Object.keys(group);
    const valueArr: any[] = Object.values(group);
    parentNames.forEach((item: string, index: number) => {
      if (item === '基本信息') {
        columns.push({
          name: item,
          align: 'center',
          lock: index == 0 ? true : false,
          width: 128,
          children: [],
        });
        return;
      }
      columns.push({
        name: (
          <div className={styles.label}>
            {item}
            <Tooltip title={tableDetailList[index]}>
              <QuestionCircleOutlined
                style={{ color: '#FD4F43', fontSize: 14, marginLeft: '4px' }}
              />
            </Tooltip>
          </div>
        ),
        align: 'center',
        lock: index == 0 ? true : false,
        width: 128,
        children: [],
      });
    });

    columns.map((colItem: any, index: number) => {
      const children: any[] = [];
      const _group: any = Object.entries(_.groupBy(valueArr[index - 1], 'secondParentName'));
      if (!index) return;

      _group.forEach((item: any) => {
        if (item[0] === 'undefined') {
          item[1].forEach((t: any) => {
            children.push({
              name: t.name,
              align: 'center',
              width: t.width,
              code: t.field,
              children: [],
              lock: index < 2,
              render: (v: any) => {
                if (t.field === 'issueStatus') {
                  if (v === '成功') {
                    return (
                      <span>
                        <CheckCircleOutlined style={{ color: '#30D485', marginRight: '4px' }} />
                        {v}
                      </span>
                    );
                  } else if (v === '失败') {
                    return (
                      <span>
                        <CloseCircleOutlined style={{ color: '#FD4F43', marginRight: '4px' }} />
                        {v}
                      </span>
                    );
                  } else {
                    return issueStatusKeys.includes(v) ? v : '-';
                  }
                }
                return v ?? '-';
              },
              features: {
                sortable:
                  index === 1
                    ? false
                    : () => {
                        return null;
                      },
              },
            });
          });
        } else {
          //三级
          children.push({
            name: item[0],
            align: 'center',
            children: item[1].map((t: any) => ({
              name: t.name,
              align: 'center',
              width: t.width,
              code: t.field,
              render: (value: any) => value || '-',
              features: {
                sortable: true,
              },
            })),
          });
        }
      });
      columns[index].children = children;
    });

    return columns;
  };
  // 处理表格数据
  const getDataSource = (dataSource: any[]) => {
    const newDataSource: any[] = [];
    dataSource.map((item, index) => {
      item.id = index + 1 + '';
      item = Object.assign(item, item.data);
      (item?.children || []).map((y: any, yIndex: number) => {
        y.id = `${index + 1}-${yIndex + 1}`;
        y = Object.assign(y, y.data);
        (y?.children || []).map((z: any, zIndex: number) => {
          z = Object.assign(z, z.data);
          z.id = `${index + 1}-${yIndex + 1}-${zIndex + 1}`;
          (z?.children || []).map((e: any, eIndex: number) => {
            e = Object.assign(e, e.data);
            e.id = `${index + 1}-${yIndex + 1}-${zIndex + 1}-${eIndex + 1}`;
          });
        });
      });
      newDataSource.push(item);
    });
    return newDataSource;
  };
  const [openKeys, onChangeOpenKeys] = useState(['']);
  const [sorts, onChangeSorts] = useState([]);
  const dataTable = _.cloneDeep(tableData);
  const [dataSource, setDataSource] = useState(getDataSource(dataTable));
  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: dataSource, columns: getColumns(tableHeader) })
    .primaryKey('id')
    .use(features.treeMode({ openKeys, onChangeOpenKeys }))
    .use(
      features.sort({
        mode: 'single',
        sorts,
        keepDataSource: true,
        onChangeSorts: (params: any) => {
          if (params.length) {
            const _dataSource = _.cloneDeep(dataSource);
            onChangeSorts(params);
            const sortData = removeEmptyRowData(
              _dataSource.splice(1),
              params[0].code,
            ).sortDataSource; // 排序数据
            const noSortData = removeEmptyRowData(_dataSource.splice(1), params[0].code).noSortData; // 不参与排序数据

            let newDataSource = [];
            if (params[0].order === SORT.desc) {
              newDataSource = sortData.sort((a: any, b: any) => {
                return b[params[0].code] - a[params[0].code];
              });
            } else {
              newDataSource = sortData.sort((a: any, b: any) => {
                return a[params[0].code] - b[params[0].code];
              });
            }
            setDataSource([_dataSource[0], ...newDataSource, ...noSortData]);
          } else {
            setDataSource(getDataSource(dataTable));
            onChangeSorts([]);
          }
        },
      }),
    );
  // 处理排序数据
  function removeEmptyRowData(data: any[], name: string) {
    const sortDataSource: any[] = [];
    const noSortData: any[] = [];
    data.map((item) => {
      if (!item || !item[name]) {
        noSortData.push(item);
      } else {
        sortDataSource.push(item);
      }
    });
    return {
      noSortData,
      sortDataSource,
    };
  }
  const customTd = ({ row, colIndex, tdProps }: any) => {
    // row 单元格的行数据
    // rowIndex 单元格的行下标
    // column 单元格的列配置
    // colIndex 单元格的列下标
    // tdProps <td> 元素的 props
    if (colIndex < 9 && row.deviationOfComprehensiveDeductionIncome < 0) {
      tdProps.style['--bgcolor'] = '#382A2C';
      tdProps.style['--hover-bgcolor'] = '#382A2C';
      return <td {...tdProps} />;
    }
    return <td {...tdProps} />;
  };
  return (
    <div className={styles.outside}>
      <AntdBaseTable
        className={[`${styles.custor}`].join(' ')}
        style={{
          '--row-height': '21px',
          '--header-row-height': '42px',
          '--cell-padding': '3px 0 4px 0',
          '--cell-border-vertical': '1px solid var(--bd-a50)',
          '--header-cell-border-vertical': '1px solid var(--bd-a50)',
        }}
        {...pipeline.getProps()}
        // defaultColumnWidth={81}
        components={{ Cell: customTd }}
        useVirtual={{ horizontal: true, vertical: true, header: false }}
      />
    </div>
  );
};

export default BaseTable;
